require('module-alias/register')
var passport = require('passport');
var { sunnyUser } = require('@Sequelize')
var LocalStrategy = require('passport-local').Strategy;
var crypto = require('crypto');
var result = crypto.createHash('md5').update('admin').digest("hex")
function md5(str){
  return crypto.createHash('md5').update(str).digest("hex")
}

passport.use(new LocalStrategy(
  function (username, password, done) {
    sunnyUser.findOne({
      where: { username: username }
     }).then(res => {
       if (!res) return done(null, false, { message: '用户名不存在.' })
       if (md5(password) !== res.password) return done(null, false, { message: '密码不匹配.' });
       return done(null, res, { message: 'success' });
    })
  }
));
passport.serializeUser(function (userInfo, done) {
  done(null, userInfo);
});

passport.deserializeUser(function (id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});


/**
 * @openapi
 * /:
 *   get:
 *     description: Welcome to swagger-jsdoc!
 *     responses:
 *       200:
 *         description: Returns a mysterious string.
 */
function authenticateLocalCallback(req, res, next) {
  console.log(req)
  console.log(res)
  console.log(next)
}
var authenticateLocal = function (req, res, next){
  return passport.authenticate('local', function (err, user, info) {
    console.log(err)
    console.log(user)
    console.log(info)
    console.log(req)
    console.log(res)
    console.log(next)
    res.send(500, { error: 'something blew up' });

  })(req, res, next)
}

module.exports = { authenticateLocal, authenticateLocalCallback, passport };
